var express = require('express');
var router = express.Router();
const dbs = require('../model/mongoose')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

router.post('/add', (req, res) => { //创建
  console.log(req.body);
  dbs.create(req.body).then(() => {
    res.send({start:200,success:true,message:'创建成功'})
  }).catch(() => {
    res.send({start:404,success:false,message:'创建失败'})
  })
});


router.post('/fdd', async (req, res) => { // 查找
  let re = new RegExp(req.body.search, 'g')  // 这一句要写在上面
  let pageNum = await dbs.count({name:re})
  let pageBtn = req.body.pageBtn
  let pageSize  =  req.body.pageSize

  //  第一页 0-5条数据    从第几条开始查 1 - 1 * 5 = 0  ((pageBtn -1 )*pageSize  = 0)  limit(5)
  //  第2页  5-10条数据     从第几条开始查 2 - 1 * 5 = 5  ((pageBtn -1 )*pageSize  = 5)  limit(5)
  //  第3页  10-15条数据     从第几条开始查 3 - 1 * 5 = 10  ((pageBtn -1 )*pageSize  = 10)  limit(5)
  


  console.log(pageBtn);
  dbs.find({name:re}).skip((pageBtn -1 )*pageSize).limit(pageSize).then((data) => {
    res.send({start:200,success:true,message:'查找成功',list:data,pageNum:pageNum})
  }).catch(() => {
    res.send({start:404,success:false,message:'查找失败'})
  })
  
});


router.get('/sdd', (req, res) => { // 删除
 dbs.remove({_id:req.query._id}).then(() => {
   res.send({start:200,success:true,message:'删除成功'})
 }).catch(() => {
   res.send({start:404,success:false,message:'删除失败'})
 })
});



router.post('/edit', (req, res) => { // 编辑
  console.log(req.body);
 dbs.update({_id:req.body._id},{$set:req.body}).then(() => {
   res.send({start:200,success:true,message:'查找成功'})
 }).catch(() => {
   res.send({start:404,success:false,message:'查找失败'})
 })
 
});


router.post('/pdd', (req, res) => { //批量 删除
  let txt = req.body
  dbs.remove({_id:{$in:txt}}).then(() => {
    res.send({start:200,success:true,message:'删除成功'})
  }).catch(() => {
    res.send({start:404,success:false,message:'删除失败'})
  })
})
module.exports = router;